package com.kylexy.closes.widge.photo;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.androidquery.AQuery;
import com.kylexy.closes.R;
import com.kylexy.closes.app.UIHelper;
import com.tl.common.util.StringUtils;


/*
 //  //使用说明 
 // //第一步: 
 //  mivVideo = (SingleVideo) findViewById(R.id.video); // 保存图片参数
 //  mivVideo.setVideo(listener, true, true); // 设置监听器
 //  mivVideo.setSavePath(FILE_SAVEPATH_VIDEO); //设置保存路径
 //  mivVideo.setFilename(XXX.jpg) ;//设置文件名 
 //  //图片不需要剪辑 
 //  mivPic.setPicture(null,true,true); 
 //  //图片需要剪辑 
 //  mivPic.setPicture(new CropParam(150, 150, true), true,true);
 //  
 //  // 第二步:图片选中事件 onPictureListener picListener = new onPictureListener() {
 //  
 //  @Override public void onPictureSelected(String url) { 
 //  // TODO Auto-generatedmethod stub 
 //           setTextData(); 
 //          } 
 //  };
 //  
 //  //第三步activity事件覆盖
 //  @Override protected void onActivityResult(int requestCode, int resultCode,
 //            Intent data) { // TODO Auto-generated method stub
 //  
 //           if (requestCode == PhotoHelper.FROM_CAMERA || requestCode ==
 //            PhotoHelper.FROM_MEDIA) { mivPic.setOnActivityResult(requestCode,
 //           resultCode, data); } super.onActivityResult(requestCode,
 //           resultCode, data); }
 //  
 //  //第四步 :如果临时图片不需要保存
 //  mivVideo.clearPic();
 */

public class SinglePicture extends RelativeLayout {
	AQuery mAquery;
	String mImgUrl;
	String mImgName;
	Context mContext;
	View mView;
	PopupWindowSelectPic mWindowSelectPic;
	PopupWindowPicZoom mWindowShowPic;
	public PhotoHelper mPhotoHelper;
	onPictureListener mListener;

	CropParam mCropParam = null;
	Boolean mShowClose = true;
	Boolean mShowBigView = true;
	int mDefautBackground = R.drawable.ic_add_smiley;
	String mSavePath = "";

	int mHeight = 120;
	int mWidth = 120;

	ImageView mivPic;

	public interface onPictureListener {
		public void onPictureSelected(String url);
	}

	public SinglePicture(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		initView(context);
	}

	public SinglePicture(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		initView(context);
		// TODO Auto-generated constructor stub
	}

	public void setPictureListener(onPictureListener listener) {
		mListener = listener;
	}

	/**
	 * 指定图片存储路径
	 * 
	 * @param savePath
	 */
	public void setSavePath(String savePath) {
		mSavePath = savePath;
		mPhotoHelper.setSavePath(savePath);
	}

	/**
	 * 设置初始化参数
	 * 
	 * @param cropParam
	 *            剪切参数 boolean showClose 是否显示删除按钮 boolean showBigView 是否点击出现图片查看
	 */
	public void setPicture(CropParam cropParam, boolean showClose,
			boolean showBigView) {
		mCropParam = cropParam;
		mShowClose = showClose;
		mShowBigView = showBigView;
	}

	public void setDefaultImg(int defaultRes) {
		mDefautBackground = defaultRes;
		mAquery.id(R.id.single_picture_pic).image(defaultRes);
	}

	public String getImageFilePath() {
		// String path = mPhotoHelper.getImageFilePath();
		// if (StringUtils.isEmpty(path)) {
		// path = mImgUrl;
		// }
		//
		// return path;

		return mImgUrl;
	}

	public String getImageFileName() {
		// String fileName = mPhotoHelper.getImageFileName();
		//
		// if (StringUtils.isEmpty(fileName)) {
		// fileName = mImgName;
		// }

		// return fileName;

		return mImgName;
	}

	public void clearPhoteCache() {
		// PhotoHelper.clearCache();
	}

	private void initView(Context context) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mView = inflater.inflate(R.layout.layout_single_picture, this);
		mView.setFocusable(false);

		mivPic = (ImageView) findViewById(R.id.single_picture_pic);

		mAquery = new AQuery(this);

		mAquery.id(R.id.single_picture_colse).clicked(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				clearPic();
			}
		});

		mivPic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				beginPic(v);
			}
		});
		mivPic.setBackgroundResource(mDefautBackground);

		// 实例化SelectPicPopupWindow
		mWindowSelectPic = new PopupWindowSelectPic((Activity) mContext,
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mWindowSelectPic.dismiss();
						mPhotoHelper.fetchPhoto(photoCallBack,
								PhotoHelper.FROM_CAMERA, mCropParam);
					}
				}, new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						mWindowSelectPic.dismiss();
						mPhotoHelper.fetchPhoto(photoCallBack,
								PhotoHelper.FROM_MEDIA, mCropParam);
					}
				});

		mPhotoHelper = new PhotoHelper((Activity) mContext);

		// mWidth = mView.getMeasuredWidth();
		// mHeight = mView.getMeasuredHeight();

	}

	public void setOnActivityResult(int requestCode, int resultCode, Intent data) {
		mPhotoHelper.onActivityResult(requestCode, resultCode, data);
	}

	public void setImg(String path, String fileName) {

		String imgFile = path + fileName;
		File origFile = new File(imgFile);
		boolean origExits = (imgFile != null && origFile.exists());
		if (origExits) {
			mImgUrl = path + fileName;
			mImgName = fileName;
			showPic();
		}
	}
	
	public void setImg(String filePath) {

		
		File origFile = new File(filePath);
		boolean origExits = (filePath != null && origFile.exists());
		if (origExits) {
			mImgUrl = filePath;
			//mImgName = fileName;
			showPic();
		}
	}

	public void popBegin() {
		mivPic.performClick();
	}

	public void setFilename(String fileName) {
		mPhotoHelper.setFileName(fileName);
	}

	/**
	 * 上传成功后图片
	 * 
	 * @param url
	 */
	private void showPic() {

		// mAquery.id(R.id.single_picture_pic).clicked(this);

		mWidth = mView.getMeasuredWidth();
		mHeight = mView.getMeasuredHeight();

		File origFile = new File(mImgUrl);
		boolean origExits = (mImgUrl != null && origFile.exists());
		if (origExits) {
			// Bitmap pic = BitmapFactory.decodeFile(url);
			// pic = ThumbnailUtils.extractThumbnail(pic, mWidth, mHeight);
			//
			// mivPic.setImageBitmap(pic);

			mAquery.id(R.id.single_picture_pic)
					.progress(R.id.single_picture_progress)
					.image(mImgUrl, false, true);

			// 显示删除按钮
			if (mShowClose)
				mAquery.id(R.id.single_picture_colse).visible();
			// UIHelper.ToastMessage(mContext, "上传图片成功,图片地址:" + url);
			// if (mListener != null)
			// mListener.onPictureSelected(mImgUrl);

			// pic.recycle();

			return;
		}

	}

	private PhotoHelper.PhotoResultCallback photoCallBack = new PhotoHelper.PhotoResultCallback() {
		@Override
		public void onResult(String path, String filename, Uri url) {
			// TODO Auto-generated method
			mImgUrl = path + filename;
			mImgName = filename;

			showPic();
			if (mListener != null)
				mListener.onPictureSelected(mImgUrl);
		}
	};

	public void clearPic() {
		try {
			mPhotoHelper.clearPic();

			mImgName = "";
			mImgUrl = "";
			mAquery.id(R.id.single_picture_pic).image(mDefautBackground);
			mAquery.id(R.id.single_picture_colse).gone();

			if (mListener != null)
				mListener.onPictureSelected("");

		} catch (Exception e) {

		}
	}

	private void beginPic(View v) {

		// 关闭输入法
		UIHelper.HideKeyBoard(mContext, v);

		if (StringUtils.isEmpty(mImgUrl)) {
			mWindowSelectPic.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
		} else if (mShowBigView) {
			// 打开浏览窗口
			mWindowShowPic = new PopupWindowPicZoom((Activity) mContext,
					mImgUrl);
			mWindowShowPic.showAtLocation(v, Gravity.CENTER, 0, 0);
		}

	}

	/**
	 * 文件改名
	 */
	public File savePic(String newFileName) {
		File file = null;
		String path = mPhotoHelper.getImageFilePath();
		if (!StringUtils.isEmpty(path)) {

			file = new File(path);
			File newFile = new File(mSavePath + newFileName + ".jpg");
			file.renameTo(newFile);
			return newFile;
		}

		return file;
	}

	public Bitmap getImage() {
		return mPhotoHelper.getImage();
	}

}
